package com.fishingwithme.infrastructure;

import com.fishingwithme.domain.user.SpotUser;
import com.fishingwithme.domain.user.UserService;
import com.fishingwithme.infrastructure.utils.CommonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class WeChatAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private WeChatService weChatService;

    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WeChatAuthenticationToken authToken = (WeChatAuthenticationToken) authentication;
        String code = (String) authToken.getPrincipal();
        String username = authToken.getUsername();
        String avatarUrl = authToken.getAvatarUrl();
        String nickName = authToken.getNickName();

        if (StringUtils.isBlank(code)) {
            throw new BadCredentialsException("微信登录码不能为空");
        }

        // 通过微信接口验证code并获取用户信息
        WeChatUserInfo userInfo = weChatService.getUserInfoByCode(code);
        if (userInfo == null) {
            throw new BadCredentialsException("微信登录失败: 无效的登录码");
        }
        userInfo.setNickName(nickName);
        userInfo.setAvatarUrl(avatarUrl);


        // 根据openid查找或创建用户
        SpotUser spotUser = userService.findOrCreateUser(userInfo);

        // 创建权限列表
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (spotUser.isAdmin()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        } else {
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }

        UserDetails userDetails = new FwmUserDetails(
                spotUser.getUserId(),
                spotUser.getUserId().toString(),
                CommonUtils.generateRandomString(8,3), // 微信登录不需要密码
                authorities,
                spotUser.getAvatarUrl(),
                spotUser.getNickname()
        );

        WeChatAuthenticationToken authenticatedToken = new WeChatAuthenticationToken(code, username, spotUser.getNickname(),spotUser.getAvatarUrl());
        authenticatedToken.setDetails(userDetails);
        authenticatedToken.setAuthenticated(true);

        return authenticatedToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WeChatAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
